package vip.xiaonuo.modular.qryNum.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.qryNum.QryNumConst;
import vip.xiaonuo.modular.qryNum.dto.NumbersJsonDto;
import vip.xiaonuo.modular.qryNum.dto.NumberExportDto;
import vip.xiaonuo.modular.util.HttpClientService;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 大网卡未注册我号码查询接口
 * @author hrd
 * @version 1.0
 * @date 2022/2/19 10:46
 */
@RestController
@Slf4j
public class QryNumController {
    @Autowired
    SysUserService userService;

    @GetMapping("/qryNum/getNumList")
    public Object getNumList(boolean useToken) throws Exception {
        String url2 = "https://m.10010.com/NumApp/NumberCenter/qryNum/guessToken?provinceCode=51&cityCode=510&monthFeeLimit=0&searchCategory=1&net=01&amounts=200&codeTypeCode=&qryType=02&goodsNet=4&goodsId=512109281389&channel=mall&guessBirthday=0703&guessIdNumber=5796&guessPhoneNumber=4760&";
        String url = "https://msgo.10010.com/NumApp/NumberCenter/qryNum?provinceCode=51&cityCode=510&monthFeeLimit=0&goodsId=512112279603&searchCategory=3&net=01&amounts=200&codeTypeCode=&searchValue=&qryType=02&goodsNet=4&channel=msg-xsg&";
        StringBuilder urlBuilder;
        if (useToken) {
            String token = userService.getUserById(LoginContextHolder.me().getSysLoginUserId()).getGetNumbersToken();
            if (StringUtils.isEmpty(token)) {
                Map<String, Boolean> map = new HashMap<>(1);
                map.put("requireToken", true);
                return map;
            }
            urlBuilder = new StringBuilder(url2);
            urlBuilder.append("token=").append(token).append("&");
        }else {
            urlBuilder = new StringBuilder(url);
        }
        urlBuilder.append("_=").append(System.currentTimeMillis()).append("&");
        urlBuilder.append(QryNumConst.JSON_CALL_BACK.name).append("=").append(QryNumConst.JSON_CALL_BACK.value).append("&");
        String result;
        try {
            result = (String) HttpClientService.sendGet(urlBuilder.toString(), null);
        }catch (Exception e) {
            log.error("qryNum/getNumList", e);
            throw new ServiceException(400, "获取号码列表失败");
        }
        if (StringUtils.isNotEmpty(result)) {
            if (result.endsWith(";")) {
                result = result.substring(0, result.length() - 1);
            }
            result = result.replace(QryNumConst.JSON_CALL_BACK.value + "(", "");
            result = result.substring(0, result.length() - 1);
            NumbersJsonDto jsonDto = JSON.parseObject(result, NumbersJsonDto.class);
            if (CollectionUtils.isEmpty(jsonDto.getNumArray())) {
                Map<String, Boolean> map = new HashMap<>(1);
                map.put("requireToken", true);
                return map;
            }
            List<String> correctNumber = jsonDto.getNumArray().stream().filter(number -> number.length() == 11).collect(Collectors.toList());
            Map<String, Object> resultMap = new HashMap<>(128);
            correctNumber.forEach(item -> {
                Map<String, Object> paramMap = new HashMap<>(2);
                Map<String, String> publicParam = new HashMap<>(8);
                publicParam.put("reqTime", String.valueOf(System.currentTimeMillis()));
                publicParam.put("reqSeq", System.currentTimeMillis() + "htSearch");
                publicParam.put("activityId", "htSearch");
                publicParam.put("appid", "cxcc7a4a1608df4431");
                publicParam.put("serviceId", "ability_customize");
                publicParam.put("version", "1.0");
                Map<String, Object> data = new HashMap<>(2);
                Map<String, String> params = new HashMap<>(2);
                params.put("mobile", item);
                data.put("params", params);
                data.put("servicecode", "Fe90322c88553590");
                paramMap.put("data", data);
                paramMap.put("publicData", publicParam);
                Map<String, String> header = new HashMap<>(16);
                for (QryNumConst value : QryNumConst.values()) {
                    header.put(value.name, value.value);
                }
                String retString = HttpClientService.doPost("https://gd.10086.cn/apph5/openapi/app/handle", JSON.toJSONString(paramMap), "utf-8", header);
                resultMap.put(item, JSON.parseObject(retString));
            });
            return resultMap;
        }
        return null;
    }

    /**
     * 大王卡获取验证码接口
     */
    @GetMapping("/gryNum/getValidateCode")
    public Object getValidateCode(String number) throws Exception {
        String url = "https://m.10010.com/ko-order/messageCaptcha/send?type=00&";
        return HttpClientService.sendGet(url + "phoneVal=" + number + "&", null, null);
    }

    @GetMapping("/gryNum/checkValidateCode")
    public Object checkValidateCode(String number, String code) {
        String url = "https://m.10010.com/mall-order/cbNumberOldCheck/check/v1";
        Map<String, String> param = new HashMap<>(16);
        param.put("phoneVal", number);
        param.put("captchaCode", code);
        param.put("type", "00");
        param.put("province", "51");
        param.put("goodsId", "512112026891");
        param.put("loginType", "0");
        param.put("salesType", "A000036V000003");
        param.put("productId", "90949377");
        param.put("salesId", "X1902221749145389");
        param.put("isNeedCard", "0");
        String result = HttpClientService.doPost(url, JSON.toJSONString(param), "utf-8", null);
        JSONObject jsonObject = JSON.parseObject(result);
        String resultCode = jsonObject.getString("code");
        if (resultCode.equals("00000")) {
            String token = jsonObject.getString("token");
            if (StringUtils.isEmpty(token)) {
                throw new ServiceException(400, "token为空");
            }
            SysUser user = userService.getUserById(LoginContextHolder.me().getSysLoginUserId());
            user.setGetNumbersToken(token);
            userService.updateById(user);
            Map<String, Object> res = new HashMap<>(1);
            res.put("success", true);
            return res;
        }else {
            String msg = jsonObject.getString("msg");
            if (StringUtils.isEmpty(msg)) {
                throw new ServiceException(400, "验证码错误");
            }else {
                throw new ServiceException(400, msg);
            }

        }
    }

    public static void main(String[] args) throws Exception {
        String url = "https://m.10010.com/mall-order/cbNumberOldCheck/check/v1";
        Map<String, String> param = new HashMap<>(16);
        param.put("phoneVal", "18688404760");
        param.put("captchaCode", "941741");
        param.put("type", "00");
        param.put("province", "51");
        param.put("goodsId", "512112026891");
        param.put("loginType", "0");
        param.put("salesType", "A000036V000003");
        param.put("productId", "90949377");
        param.put("salesId", "X1902221749145389");
        param.put("isNeedCard", "0");
        String result = HttpClientService.doPost(url, JSON.toJSONString(param), "utf-8", null);
        System.out.println(result);

    }
    @PostMapping("/qryNum/export")
    public void export(@RequestBody List<String> data) {
        List<NumberExportDto> collect = data.stream().map(NumberExportDto::new).collect(Collectors.toList());
        PoiUtil.exportExcelWithStream("number.xls", NumberExportDto.class, collect);
    }
}
